package com.youhong.teethcare;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.youhong.cuptime.blesdk.BleService;
import com.youhong.teethcare.services.BackgroundRunningHelp;
import com.youhong.teethcare.services.Common;
import com.youhong.teethcare.dialogs.DeviceNotFoundDialog;
import com.youhong.teethcare.utils.AppManager;
import com.youhong.teethcare.utils.BraceletDevice;
import com.youhong.teethcare.utils.DialogUtil;
import com.youhong.teethcare.utils.ToastUtil;

import java.util.Calendar;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    TextView tv_dashBoard, tv_brushing, tv_history, tv_setting;
    FrameLayout fl_container;
    protected Fragment fragment_dashBoard,
            fragment_brushing, fragment_history, fragment_setting;

    public static boolean isBrushingStart = false;
    public static boolean isBrushWork = false;

    //主动断开连接时，应将MainActivity.mDevice 赋值为Null
    public static BraceletDevice mDevice;
    ProgressDialog connectDialog;
    //连接方法，主页上所有的Fragment 连接设备都需要通过这个接口，
    //这样可以把连接前的蓝牙判断代码都写入这个方法内。
    public boolean doomPrompt = false;

    public void connect() {

        if (Common.userInfo.getMac() == null || Common.userInfo.getMac().equals("")) {
            //Toast.makeText(getApplicationContext(), R.string.strings21, Toast.LENGTH_SHORT).show();
            return;
        }

        //如果设备已经处于连接状态，则断开
        if (MainActivity.mDevice != null && MainActivity.mDevice.isConnected()) {
//
//            MainActivity.mDevice.disconnectedDevice();
//            MainActivity.mDevice = null;
//
//            if (doomPrompt) {
//
//                doomPrompt = false;
//
//            } else {
//                ToastUtil.showShortToast(getApplicationContext(), R.string.strings113);
//            }
        } else {

            if (!DialogUtil.getBleStatus(getApplicationContext().getApplicationContext())) {
                DialogUtil.enableBluetooth(this);
                return;
            }

            MainActivity.mDevice =
                    new BraceletDevice(getApplicationContext().getApplicationContext(),
                            Common.userInfo.getMac());

            if (connectDialog == null) {
                //创建正在连接的Dialog。
                connectDialog = DialogUtil.showDialog(this, R.string.strings19);
            }
            //显示Dialog
            connectDialog.show();
            //15秒之内没有连接上设备，就隐藏正在连接Dialog
            handler.postDelayed(runnable_connectDialogWatchDog, 20000);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            moveTaskToBack(true);//最小化
            return true;
        } else if(keyCode == KeyEvent.KEYCODE_MENU) {
            //监控/拦截菜单键
            moveTaskToBack(true);//最小化
            return true;
        } else if(keyCode == KeyEvent.KEYCODE_HOME) {
            //由于Home键为系统键，此处不能捕获，需要重写onAttachedToWindow()
            moveTaskToBack(true);//最小化
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == DialogUtil.REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
            //如果此时还未绑定设备，提示用户去绑定
            if (TextUtils.isEmpty(Common.userInfo.getMac())) {
                ToastUtil.showShortToast(getApplicationContext(), R.string.strings21);
                return;
            }

            MainActivity.mDevice =
                    new BraceletDevice(getApplicationContext().getApplicationContext(),
                            Common.userInfo.getMac());

            if (connectDialog == null) {
                //创建正在连接的Dialog。
                connectDialog = DialogUtil.showDialog(this, R.string.strings19);
            }

            //显示Dialog
            connectDialog.show();
            //15秒之内没有连接上设备，就隐藏正在连接Dialog
            handler.postDelayed(runnable_connectDialogWatchDog, 15000);
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    //连接牙刷失败时失败用于提示用户的Dialog
    Dialog not_found_dialog;

    //该Dialog 右上角的关闭按钮的Callback
    Runnable runnable_iv_close = new Runnable() {
        @Override
        public void run() {
            not_found_dialog.dismiss();

        }
    };

    Runnable runnable_connectDialogWatchDog = new Runnable() {
        @Override
        public void run() {

            //connectDialog.hide();
            if (connectDialog != null) {
                connectDialog.dismiss();
                connectDialog = null;

            }
            if (not_found_dialog == null) {
                not_found_dialog = new DeviceNotFoundDialog(MainActivity.this, runnable_iv_close);

            }
            not_found_dialog.show();

            //Toast.makeText(getApplicationContext(), R.string.strings20, Toast.LENGTH_SHORT).show();
            mDevice.disconnectedDevice();
            mDevice = null;
        }
    };

    Handler handler = new Handler();

    //给BrushingFragment 做的通信函数，用来刷牙完成后切换至HistoryFragment
    protected void switchToHistoryFragment() {

        ((HistoryFragment) fragment_history).setSelected_date(Calendar.getInstance());
        onClick(tv_history);
    }
    protected void switchToBrushFragment() {


        onClick(tv_brushing);
    }
    boolean isBackPressed = false;

    @Override
    public void onBackPressed() {

        if (!isBackPressed) {

            isBackPressed = true;
            Toast.makeText(this, R.string.strings95, Toast.LENGTH_SHORT).show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isBackPressed = false;
                }
            }, 3000);
        } else {

            handler.removeCallbacksAndMessages(null);
            //退出APP， 使用System.Exit() 退出，部分机型会出现闪退提示。
            AppManager.getInstance().killAllActivity();

        }
    }

    @Override
    public void finish() {
        super.finish();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置FirstTimeIn = true

        Common.userInfo.SyncToLocal(getApplicationContext());

        AppManager.getInstance().killAllActivity();
        AppManager.getInstance().addActivity(this);

        setContentView(R.layout.activity_main);
        filter = new IntentFilter();
        filter.addAction(BleService.ACTION_GATT_SERVICES_DISCOVERED);
        filter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        filter.addAction(BleService.ACTION_DATA_AVAILABLE);

        registerReceiver(receiver, filter);
        getViews();
        checkExternalStoragePermission();
        connect();
    }

    private void checkExternalStoragePermission() {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

        } else {
            // Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show();
            Log.e("asdsad", "checkPermission: 已经授权！");
        }
    }



    IntentFilter filter;

    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiver);
    }

    private void getViews() {
        unSelectedColor=getResources().getColor(R.color.mainTextUnSelectedColor);
        tv_dashBoard = findViewById(R.id.main_tv_dashBoard);
        tv_dashBoard.setOnClickListener(this);

        tv_brushing = findViewById(R.id.main_tv_brushing);
        tv_brushing.setOnClickListener(this);

        tv_history = findViewById(R.id.main_tv_history);
        tv_history.setOnClickListener(this);

        tv_setting = findViewById(R.id.main_tv_setting);
        tv_setting.setOnClickListener(this);

        fragment_dashBoard = new DashBoardFragment();
        fragment_brushing = new BrushingFragment();
        fragment_history = new HistoryFragment();
        fragment_setting = new SettingFragment();


        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.main_fl_container, fragment_dashBoard);
        //设置Previous Fragment
        previous_fragment = fragment_dashBoard;

        //初始时就加载History 页面，Hide掉。
        ft.add(R.id.main_fl_container, fragment_history);
        ft.hide(fragment_history);

        ft.commit();
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction() == BleService.ACTION_GATT_SERVICES_DISCOVERED) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //connectDialog.cancel();
                        handler.removeCallbacksAndMessages(null);
                        // connectDialog.hide();

                        if (connectDialog != null) {

                            connectDialog.dismiss();
                            connectDialog = null;
                        }

                        //连接成功后，立刻同步时间
                        MainActivity.mDevice.syncTime(Calendar.getInstance());
                    }
                });
            } else if (intent.getAction() == BleService.ACTION_DATA_AVAILABLE) {

                byte[] values = intent.getByteArrayExtra(BleService.EXTRA_DATA);

                if (values[0] == (byte) 0x28 && values[1] == (byte) 0x88) {
                    //如果当前页面不在BrushingFragment ，就跳转到BrushingFragment并启动刷牙
                    if (!(previous_fragment instanceof BrushingFragment)) {
                        onClick(tv_brushing);

                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ((BrushingFragment) fragment_brushing).brushProgress((byte) 0x88, (byte) 0);

                            }
                        }, 500);
                    }
                }else if(values[0]==(byte)0x01){
                    if (MainActivity.mDevice != null) {
                        MainActivity.mDevice.getBattery();

                    }
                }
            }
        }

    };

    Fragment previous_fragment;

    @Override
    public void onClick(View v) {


        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
     //   ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

        if (v == tv_dashBoard) {
            initStatusBar(getResources().getColor(R.color.mainColor),false);

            if (MainActivity.isBrushingStart) {

                brushingSwitchNotification(v);
                return;
            }

            //本次点击的就是当前页面
            if (previous_fragment instanceof DashBoardFragment) {
                return;
            }
            switchFragment(ft,fragment_dashBoard,tv_dashBoard,R.mipmap.icon_dashboard_selected);

        } else if (v == tv_brushing) {
            initStatusBar(getResources().getColor(R.color.mainColor),false);

            //本次点击的就是当前页面
            if (previous_fragment instanceof BrushingFragment) {

                return;
            }


            switchFragment(ft,fragment_brushing,tv_brushing,R.mipmap.icon_brushing_selected);

        } else if (v == tv_history) {
            initStatusBar(getResources().getColor(R.color.pageBackground),true);

            if (MainActivity.isBrushingStart) {

                brushingSwitchNotification(v);
                return;
            }


            //本次点击的就是当前页面
            if (previous_fragment instanceof HistoryFragment) {

                return;
            }

            switchFragment(ft,fragment_history,tv_history,R.mipmap.icon_history_selected);
        } else if (v == tv_setting) {
            initStatusBar(getResources().getColor(R.color.mainColor),false);

            if (MainActivity.isBrushingStart) {

                brushingSwitchNotification(v);
                return;
            }

            //本次点击的就是当前页面
            if (previous_fragment instanceof SettingFragment) {

                return;
            }

            switchFragment(ft,fragment_setting,tv_setting,R.mipmap.icon_setting_selected);
        }
        try {
            ft.commit();

        } catch (Exception exo) {

        }

    }
    void switchFragment( FragmentTransaction ft,Fragment fragment,TextView textView,int drawableId){
        unselectedAll();
        switchFragment(previous_fragment,ft);
        previous_fragment = fragment;
        Drawable dw = getResources().getDrawable(drawableId);
        dw.setBounds(0, 0, dw.getIntrinsicHeight(), dw.getIntrinsicHeight() - clipHeightt);
        if(textView==tv_history){
            ft.show(fragment);
        }else {
            ft.add(R.id.main_fl_container, fragment);
        }

        textView.setCompoundDrawables(null, dw, null, null);
        textView.setTextColor(Color.parseColor("#00BFC6"));
    }

    private void brushingSwitchNotification(View view) {
        DialogUtil.showModalDialog(MainActivity.this, R.string.strings97, R.string.strings96, R.string.strings98, R.string.strings99
                , new Runnable() {
                    @Override
                    public void run() {

                        MainActivity.isBrushingStart = false;
                        long c_end = System.currentTimeMillis();

                        long c_start = ((BrushingFragment) fragment_brushing).c_start;
                        long previos_brushTime = ((BrushingFragment) fragment_brushing).previousBrushTime;
                        if (c_end - c_start + previos_brushTime >= 30000) {
                            //保存记录，并由BrushingFragment再次通知MainActivity,去跳转至历史数据页面
                            ((BrushingFragment) fragment_brushing).mainActivityFinishBurshing();

                        } else {

                            //如果刷牙时长小于30s ，则不保存历史数据，直接跳至所点击的页面
                            onClick(view);
                        }
                    }
                }, null);
    }

    //四个Fragment，有哪些页面在不点击开的时候保留它的状态(ft.Detach()) 哪些页面
    //不保留它的状态(ft.Remove()).

    private void switchFragment(Fragment previous,FragmentTransaction ft) {


        if (previous == null)
            return;

        //主页不保留，Remove 掉。
        if (previous instanceof DashBoardFragment) {

            ft.remove(previous);

            //实时刷牙页面也不保留Remove 掉.
        } else if (previous instanceof BrushingFragment) {

            ft.remove(previous);

        } else if (previous instanceof HistoryFragment) {
            //保留历史页状态,只Hidden

            ft.hide(previous);

            //设置页面不保留
        } else if (previous instanceof SettingFragment) {

            ft.remove(previous);
        }
        try {
            ft.commit();

        } catch (Exception exp) {

        }
    }

    int clipHeightt = 5;
    int unSelectedColor;
    public void unselectedAll() {
        setUnSelectedState(R.mipmap.icon_history,tv_history);
        setUnSelectedState(R.mipmap.icon_brushing,tv_brushing);
        setUnSelectedState(R.mipmap.icon_dashboard,tv_dashBoard);
        setUnSelectedState(R.mipmap.icon_setting,tv_setting);
    }
    void setUnSelectedState(int resId,TextView textView){
        Drawable draw4 = getResources().getDrawable(resId);
        draw4.setBounds(0, 0, draw4.getIntrinsicWidth(), draw4.getIntrinsicHeight() - clipHeightt);
        textView.setCompoundDrawables(null, draw4, null, null);
        textView.setTextColor(unSelectedColor);
    }
}